<template>
  <a-modal
    width='945px'
    title='编辑访问控制'
    cancelText="取消"
    okText="确定"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel">
    <a-form>
      <a-button class="addBtn" @click="addUser()">添加参与者</a-button>
      <a-button class="delBtn" @click="delRoot()">移除参与者</a-button>
      <a-table style="margin-top: 10px;" rowKey="name"
               :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange ,getCheckboxProps: getCheckboxProps,}"
               :columns="accessControlArr" :dataSource="tableData" :pagination="tablePaginationPeople">
        <template slot="root" slot-scope="record">
          <a-checkbox @change.native="onChange(item, record)" v-for="(item, index) in record" :key="index"
                      v-model="item.have">{{ item.display }}
          </a-checkbox>
        </template> 
      </a-table>
    </a-form>
    <commElAdduser v-if="showAddUser" ref="commElAdduser" @initDataList='initData' @closeUser="closeUser"/>
  </a-modal>
</template>
<script>
import {mapGetters} from 'vuex'
import {findUserAllAccessForObj, grantAccess} from "@/api/fileSingle.js"
import commElAdduser from "./comm-el-adduser.vue";
let userinfo = JSON.parse(sessionStorage.getItem('userInfo'))
export default {
  data() {
    return {
      userInfo:JSON.parse(sessionStorage.getItem('userInfo')),
      visible: false,
      controlAuthorityArr: [],
      accessControlArr: [
        {
          title: '参与者',
          key: 'name',
          dataIndex: 'name',
        },
        {
          title: '权限',
          dataIndex: 'root',
          scopedSlots: {customRender: 'root'},
        }],
      tableData: [],
      plainOptions: ['读取', '下载', '修改', '修改内容', '更改权限'],
      selectedRowKeys: [],
      checkedList: [],
      checkAll: false,
      indeterminate: false,
      showAddUser: false,//添加参与者
      tablePaginationPeople: {
        pageSize: 5,
      },//参与者分页
    }
  },
  components: {
    commElAdduser
  },
  computed: {
    ...mapGetters({
      'fileSingleData': 'fileSingle'
    })
  },
  methods: {
    /**
     * name: delRoot 移除参与者
     */
    delRoot() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.error('请选择您所需要删除的参与者')
        return
      }
      this.selectedRowKeys.forEach(name => {
        this.tableData.forEach((item, index) => {
          if (name === item.name) {
            this.tableData.splice(index, 1)
          }
        })
      })
    },
    /**
     * name: addUser 开启子组件comm-el-addUser.vue
     */
    addUser() {
      this.showAddUser = true
    },
    closeUser() {
      this.showAddUser = false
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // 默认选中
    getCheckboxProps(record) {
      return ({
        props: {
          disabled: record.name == userinfo.id, // Column configuration not to be checked
          name: '',
        },
      });
    },
    /**
     * name: initData table数据初始化
     */
    initData(userIds) {
      userIds.push((userinfo.id).toString())
      // console.log('userIds:', userIds)
      this.tableData = []
      let fileItem = this.fileSingleData.tableArr[0]
      // let data = this.getRoot(fileItem.oid, userinfo.loginName)
      for (let i = 0; i < userIds.length; i++) {
        this.getRoot(fileItem.oid, userIds[i])
      }
      console.log('---第一次点进来的数据',this.tableData)
      this.selectedRowKeys = []
      this.showAddUser = false
    },
    /**
     * 获取某一个oid权限
     */
    getRoot(oid, uid) {
      findUserAllAccessForObj({objOid: oid, principalOid: uid}).then((res) => {
        if (res && res.data.success) {
          // let data = {name: name, root: res.data.data}
          let data = {name: uid, root: res.data.data}
          this.tableData.push(data)
        }
      })
    },
    /**
     * 点击表格中的复选框获取数据
     */
    onChange(e, rootlist) {
      if (e.name === 'ALL') {
        rootlist.forEach(item => {
          item.have = e.have ? true : false
        })
      }
      /*rootlist = rootlist.filter((rec)=>{
        return rec.have == true
      })
      console.log('选择的----',rootlist)*/
    },
    /**
     * 点击“确定”保存控制权限
     */
    handleOk() {
      console.log('1111111')
       //console.log('this.tableData---', this.tableData);
      // for (let i = 0; i < this.tableData.length > 0; i++) {
      //   let assNo = this.tableData[i].root.filter((rec) => {
      //     return rec.have === true
      //   })
      //   let acceNo = assNo.map((rec)=>{
      //     return rec.accessNo.toString()
      //   })
      //    console.log('acceNo----',acceNo)
      // }
      let tableArr = this.tableData.map((e)=>{
        let acceNo = [];                           //设置权限的数组
        e.root.forEach((item)=>{
             if(item.have==true){
               acceNo.push(item.accessNo);
             }
           })
        return {
          "principalOid" :e.name,
           "accessNos" : acceNo
        }
      });
      let params= {
           "oid": this.fileSingleData.tableArr[0].oid,
           "data": tableArr
        }
       // console.log('设置权限的数据',params);
        //console.log(params);
       // grantAccess({objOid: this.fileSingleData.tableArr[0].oid, principalOid: this.tableData[i].name,accessNos:acceNo}).then((res) => {
         grantAccess(params).then((res) => {
          if (res && res.status==200) {
            if(res.data && res.data.success){
              this.$message.success('权限控制设置成功！')
              
            }else{
              this.$message.error(res.data.message)
            }
          }else{
            this.$message.error('接口失败!')
          }
        })
        
        this.$emit('initTableData', 'ControlAuthority');
      this.visible = false
    },
    handleCancel() {
      this.visible = false
    },
    /**
     * 开启弹窗
     * key 上级需要开启那个弹窗的key props上级tree选中的tree，propsArr 上级table选中的数据
     */
    openModal(start, props, propsArr) {
      this.visible = start
      this.controlAuthorityArr = propsArr
      this.initData([])
    }
  }
}
</script>
<style lang="less" scoped>
.addBtn,
.delBtn {
  width: 120px;
  height: 32px;
  background: #FFFFFF;
  border: 1px solid #CCCCCC;
  border-radius: 4px;
  margin-top: -14px;
}
.addBtn {
  margin-right: 9px;
}
</style>